<!DOCTYPE HTML>
<html lang="zh-CN">




<head>
    <meta charset="utf-8">
    <meta name="keywords" content="springJPA, 深度学习 故障诊断 Java">
    <meta name="description" content="河海大学 | 计算机与信息学院 | 信号与信息处理">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>springJPA | 世庆的博客</title>
    <link rel="icon" type="image/png" href="/shiqing/favicon.png">

    <link rel="stylesheet" type="text/css" href="/shiqing/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/my.css">

    <script src="/shiqing/libs/jquery/jquery.min.js"></script>

    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 6.3.0"></head>




    <body>
        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/shiqing/" class="waves-effect waves-light">
                    
                    <img src="/shiqing/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">世庆的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/shiqing/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">世庆的博客</div>
        <div class="logo-desc">
            
            河海大学 | 计算机与信息学院 | 信号与信息处理
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/sqtian-hhu/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/sqtian-hhu/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

        



<div class="bg-cover pd-header post-cover" style="background-image: url('/shiqing/medias/featureimages/22.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">springJPA</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/shiqing/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/shiqing/tags/SpringJPA/">
                                <span class="chip bg-color">SpringJPA</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/shiqing/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-04-23
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/shiqing/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>day1：orm思想和hibernate以及jpa的概述和jpd的基本操作<br>day2：springdatajpa的运行原理以及基本操作<br>day3：多表操作，复杂查询</p>
<p>##day1<br>第一：orm（对象关系映射）思想<br>    主要目的：操作实体类就相当于操作数据库表<br>    需要建立两个映射思想：<br>        1. 建立实体类和表的关系<br>        2. 建立实体类中属性和表中字段的关系<br>    不再重点关注：sql语句</p>
<pre><code>实现了ORM思想的框架：mybatis（半自动orm）， hibernate
tk.mybatis.mapper 插件
</code></pre>
<p>第二：hibernate框架介绍<br>    hibernate是一个开源的对象关系映射框架，它对JDBC进行了非常轻量级的对象封装，<br>它将pojo与数据库表建立映射关系，是一个全自动的orm框架，可以自动生成SQL语句，自动执行。</p>
<p>第三：JPA规范<br>    内部由接口和抽象类构成，所有厂商实现jpa规范</p>
<p>第四：jpa的基本操作<br>    增删改查<br>    搭建环境的过程<br>        1. 创建maven工程导入坐标<br>        2. 需要配置jpa的核心配置文件<br>            配置到类路径下的META-INF的文件夹下<br>            命名：persistence.xml<br>        3. 编写客户的实体类<br>        4. 配置实体类和表，类中属性和表中字段的映射关系<br>        5. 保存客户到数据库中<br>    Jpa操作步骤：<br>        @Test<br>        public void testSave(){<br>            &#x2F;&#x2F;1. 加载配置文件创建工厂（实体管理类工厂）对象<br>            EntityManagerFactory factory &#x3D; Persistence.createEntityManagerFactory(“myJpa”);<br>            &#x2F;&#x2F;2. 通过实体管理类工厂获取实体管理类<br>            EntityManager em &#x3D; factory.createEntityManager();<br>            &#x2F;*<br>                createEntityManager()方法内部维护了数据库信息，缓存信息，所有的实体管理类对象<br>                在创建EntityManagerFactory的过程中会根据配置创建数据库表<br>                EntityManagerFactory的创建过程比较浪费资源<br>                特点：线程安全的对象<br>                    多个线程访问同一个emfactory不会有线程安全问题<br>                    创建一个公共的emfactory的对象，使用静态代码块<br>            *&#x2F;<br>            &#x2F;&#x2F;3. 获取事务对象，开启事务<br>            EntityTransaction tx &#x3D; em.getTransaction();<br>            tx.begin();<br>            &#x2F;&#x2F;4. 完成增删改查操作<br>            User user &#x3D; new User();<br>            user.setUsername(“tsq”);<br>            user.setPassword(“lcc”);<br>            &#x2F;&#x2F;保存<br>            em.persist(user);<br>            &#x2F;&#x2F;5. 提交事务<br>            tx.commit();<br>            &#x2F;&#x2F;6. 释放资源<br>            em.close();<br>            factory.close();<br>            }<br>        }</p>
<p>&#x2F;**</p>
<ul>
<li>解决实体管理类工厂的浪费和耗时问题</li>
<li>通过静态代码块创建公共实体管理类工厂</li>
<li></li>
<li>第一次访问getEntityManager方法: 经过静态代码创建一个factory对象,再调用方法创建一个EntityManger对象</li>
<li>第二次访问: 直接通过已经创建好的factory对象创建EntityManager对象</li>
<li> *&#x2F;<br>public class JpaUtils { private static EntityManagerFactory factory; static{<pre><code> factory = Persistence.createEntityManagerFactory(&quot;myJpa&quot;);
</code></pre>
 } public static EntityManager getEntityManager(){<br> return factory.createEntityManager();<br> }</li>
</ul>
<p>}</p>
<pre><code>/**
 * 根据id查询客户
 */
@Test
public void testGetReference()&#123;
    //1. 通过工具类获取entityManager
    EntityManager entityManager = JpaUtils.getEntityManager();
    //2. 开启事务
    EntityTransaction tx = entityManager.getTransaction();
    //3. 增删改查
    /**
     * find: 根据id查询数据
     *      class: 查询数据的结果需要包装的实体类类型字节码
     *      id: 查询的主键的取值
     *      1. 获取的对象就是当前客户对象本身
     *      2. 在调用find方法的时候,就会发送sql语句查询数据库
     *      立即加载
     *
     * getReference方法
     *      1. 获取的对象是一个动态代理对象
     *      2. 调用getReference方法不会立即发送sql语句查询数据库
     *          延迟加载,当调用查询结果对象的时候,才会发送查询的sql语句: 什么时候用,什么时候发送sql语句查询数据库
     *
     */
    User user = entityManager.getReference(User.class,1);
    System.out.println(user);
    //4. 提交事务
    tx.commit();
    //5. 释放资源
    entityManager.close();

&#125;
</code></pre>
<p>}</p>
<pre><code>/**
 * 查询全部
 *  jpql: from com.sqtian.domain.User
 *  sql: select * from user
 */

@Test
public void testFindAll()&#123;
    //1. 获取em
    EntityManager em = JpaUtils.getEntityManager();
    //2. 开启事务
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    //3. 查询全部
    String jpql = &quot;from com.sqtian.domain.User&quot;;
    Query query = em.createQuery(jpql);//创建Query查询对象,query对象才是执行jqpl的对象

    //发送查询,并封装结果集
    List resultList = query.getResultList();
    for (Object o : resultList) &#123;
        System.out.println(o);
    &#125;
    //4. 提交事务
    tx.commit();
    //5. 释放资源
    em.close();
&#125;
</code></pre>
<p>添加分页limit查询<br>        String jpql &#x3D; “from com.sqtian.domain.User”;<br>        Query query &#x3D; em.createQuery(jpql);&#x2F;&#x2F;创建Query查询对象,query对象才是执行jqpl的对象</p>
<pre><code>    //对参数赋值: 分页参数
    //起始索引
    query.setFirstResult(0);
    //每页查询条数
    query.setMaxResults(2);

    //发送查询,并封装结果集
    List resultList = query.getResultList();
    for (Object o : resultList) &#123;
        System.out.println(o);
    &#125;
</code></pre>
<p>&#x2F;&#x2F;对占位符参数赋值		<br>String jpql &#x3D; “from User where custName like ？”；<br>Query query &#x3D; em.createQuery(jpql);<br>&#x2F;&#x2F;占位符的索引位置, 取值<br>query.setParameter(1,”lcc%”);</p>
<h2 id="day2：springdatajpa的运行原理以及基本操作"><a href="#day2：springdatajpa的运行原理以及基本操作" class="headerlink" title="day2：springdatajpa的运行原理以及基本操作"></a>day2：springdatajpa的运行原理以及基本操作</h2><p>第一 springDataJpa的概述<br>    Spring Data JPA 是Spring 基于ORM框架, JPA规范的基础上封装的一套JPA应用框架<br>    可以让开发者解脱DAO层的操作,基本上所有的CRUD都可以依赖于它来实现,在实际的工作工程中<br>    推荐使用Spring Data JPA + ORM(hibernate)完成操作</p>
<p>第二 springDataJpa的入门操作<br>    搭建环境<br>        创建工程导入坐标<br>        配置spring的配置文件<br>        编写实体类(Customer), 使用jpa注解配置映射关系<br>    编写一个符合springDataJpa的dao层接口<br>        只需要编写dao层接口，不需要编写dao层接口的实现类<br>        dao层接口规范<br>            需要继承两个接口： JpaRepository，JpaSepecificationExecutor<br>            需要提供相应的泛型<br>            真正发挥作用的是接口的实现类，在程序执行的过程中，自动帮助我们动态的生成了接口的实现类对象<br>            动态代理<br>@RunWith(SpringJUnit4ClassRunner.class)&#x2F;&#x2F;声明spring提供的单元测试环境<br>@ContextConfiguration(locations &#x3D; “classpath:applicationContext.xml”)&#x2F;&#x2F;指定spring容器的配置信息<br>public class UserDaoTest {<br>    @Autowired<br>    private UserDao userDao;</p>
<pre><code>/**
 * 根据id查询
 */
@Test
public void testFindOne()&#123;
    User one = userDao.findOne(1);
    System.out.println(one);
&#125;

/**
 * save(user)： 保存或者更新
 *  根据传递对象是否存在主键id
 *  如果没有id主键属性： 保存
 *  存在id主键属性： 根据id查询数据，更新数据
 * delete(id): 根据id删除
 * findAll(): 查询所有
 */
</code></pre>
<p>}</p>
<p>第三 springDataJpa的运行过程和原理剖析<br>    1. 通过JdkDynamicAopProxy的invoke方法创建了一个动态代理对象<br>    2. SimpleJpaRepository当中封装了JPA的操作（借助JPA的api完成数据库的CRUD）<br>    3. 通过hibernate完成数据库操作（封装了jdbc）</p>
<p>第四 复杂查询<br>    1. 借助接口中定义的方法<br>    findOne(id): 根据id查询 立即加载<br>    getOne(id): 懒加载<br>    count(): 查询全部客户数量<br>    exists(id): 查询该id客户是否存在</p>
<pre><code>2. 需要将JPQL语句配置到接口方法上
    特有的查询：需要在dao接口上配置方法
    在新添加的方法上，使用@Query注解的形式配置jpql查询语句

    对于多个占位符参数,赋值默认情况下占位符的位置需要和方法参数中的位置保持一致
    可以指定占位符参数的位置, ?1 ?2 指定取值来源
    
    
    更新数据
     /**
     * 更新操作
     */
    @Query(value = &quot;update User set username = ?2 where id = ?1&quot;)
    @Modifying
    void updateUser(int id,String username);

3. sql语句的查询
    注解:
    @Query(value=&quot;&quot;, nativeQuery = (false: 使用jpql查询, true: 使用sql查询))

4. 方法名称规则查询
    是对jpql查询更加深入的一层封装
    无需注解添加语句,只需要按照SpringDataJpa提供的方法名称规则定义方法,不需要再去配置jpql语句,完成查询
    
    findByXXX: 查询
        对象中的属性名,查询条件
        findByUsername
        在springdataJpa运行阶段会根据方法名称进行解析
    findBy + 属性名称 + 查询方式(Like|isnull)
        findByXXXLike: 模糊查询
    findBy + 属性名称 + 查询方式 + 多条件的连接符(and|or) + 属性名称 + 查询方式 
    
    
    
    
    
    
</code></pre>
<h2 id="day3"><a href="#day3" class="headerlink" title="day3"></a>day3</h2><p>第一：Specifications动态查询<br>    方法<br>    T findOne(Specification<T> spec); &#x2F;&#x2F;查询单个对象<br>    List<T> findAll(Specification<T> spec); &#x2F;&#x2F;查询列表</p>
<pre><code>//查询全部, 分页 pageable: 分页参数
//返回值: 分页pageBean
Page&lt;T&gt; findAll(Specification&lt;T&gt; spec, Pageable pageable);

//查询列表
List&lt;T&gt; findAll(Specification&lt;T&gt; spec); //统计查询

Specification: 查询条件
    自定义我们自己的Specification实现类
    实现 
        //root: 查询的根对象(查询的任何属性都可以从根对象中获取)
        //CriteriaQuery: 顶层查询对象, 自定义查询方式(了解: 一般不用)
        //CriteriaBuilder: 查询的构造器,封装了很多的查询条件
        Predicate toPredicate(Root&lt;T&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb); //封装查询条件
        
@Test
public void testSpec()&#123;
    /**
     * 自定义查询条件
     *      1. 实现Specification接口（提供泛型： 查询对象类型）
     *      2. 实现toPredication方法（构造查询条件）
     *      3. 需要借助方法参数中的两个参数（
     *          root： 获取需要查询的对象属性
     *          CriteriaBuilder： 构造查询条件， 内部封装了很多查询条件（模糊匹配，精准匹配）
     *
     */
    Specification&lt;User&gt; spec = new Specification&lt;User&gt;() &#123;
        public Predicate toPredicate(Root&lt;User&gt; root, CriteriaQuery&lt;?&gt; criteriaQuery, CriteriaBuilder criteriaBuilder) &#123;
            //1. 获取比较的属性
            Path&lt;Object&gt; username = root.get(&quot;username&quot;);
            //2. 构造查询条件　select * from user where username = &quot;tsq&quot;
            Predicate predicate = criteriaBuilder.equal(username, &quot;tsq&quot;);//进行精准匹配 （比较的属性，比较的属性的取值）
            return predicate;
        &#125;
    &#125;;
    User one = userDao.findOne(spec);
    System.out.println(one);
&#125;



        /**
         * 多条件查询
         *
         */
        Specification&lt;User&gt; spec = new Specification&lt;User&gt;() &#123;
            public Predicate toPredicate(Root&lt;User&gt; root, CriteriaQuery&lt;?&gt; criteriaQuery, CriteriaBuilder criteriaBuilder) &#123;
                //1. 获取比较的属性
                Path&lt;Object&gt; username = root.get(&quot;username&quot;);
                Path&lt;Object&gt; password = root.get(&quot;password&quot;);
                //2. 构造查询条件　select * from user where username = &quot;tsq&quot; and password = &quot;123&quot;
                Predicate predicate1 = criteriaBuilder.equal(username, &quot;tsq&quot;);//进行精准匹配 （比较的属性，比较的属性的取值）
                Predicate predicate2 = criteriaBuilder.equal(username, &quot;123&quot;);
                //3. 组合多个查询条件　cb.and  cb.or
                Predicate predicate = criteriaBuilder.and(predicate1, predicate2);

                return predicate;
            &#125;
        &#125;;
        
        /**
        * 模糊查询
        */
        equal: 直接得到path对象进行比较即可
        gt, ge, le, like: 得到path对象之后,根据path指定比较的参数类型,再去进行比较 path.as(类型的字节码对象)
        
        Predicate predicate = criteriaBuilder.like(username.as(String.class), &quot;ts%&quot;);
        
        //排序
        Sort sort = new Sort(Sort.Direction.DESC,&quot;id&quot;);
        List&lt;USer&gt; list = userDao.findAll(spec,sort);
        
        //分页查询
        Pageable pageable = new PageRequest(0,2);
        
</code></pre>
<p>第二：多表之间的关系和操作多表的操作步骤<br>    表关系:<br>        一对一<br>        一对多<br>            一的一方: 主表<br>            多的一方: 从表<br>            外键: 需要在从表上新建一列作为外键,他的取值来源于主表的主键</p>
<pre><code>    多对多
实体类中的关系:
    包含关系: 可以通过实体类中的包含关系描述表关系
    继承关系

分析步骤:
    1. 明确表关系
    2. 确定表关系 (描述 外键|中间表)
    3. 编写实体类, 在实体类中描述表关系(包含关系)
    4. 配置映射关系
</code></pre>
<p>第三：完成多表操作</p>
<ol>
<li><p>一对多操作<br> 一个客户可以有多个联系人<br> 主表: 客户表<br> 从表: 联系人表<br> 在从表上添加外键<br><br><br> &#x2F;**</p>
<ul>
<li>在联系人类里配置联系人到客户的多对一关系</li>
<li><pre><code> 使用注解的形式配置多对一关系
</code></pre>
</li>
<li><pre><code> 1. 配置表关系
</code></pre>
</li>
<li><pre><code> 2. 配置外键
</code></pre>
</li>
<li>  *&#x2F;</li>
</ul>
<p> @ManyToOne(targetEntity &#x3D; User.class)<br> @JoinColumn(name &#x3D; “lkm_usr_id”,referencedColumnName &#x3D; “id”)<br> private User user;</p>
<p> &#x2F;&#x2F;在客户类里配置客户和联系人之间的关系（一对多关系）<br> &#x2F;**</p>
<ul>
<li>使用注解形式配置多表关系</li>
<li><pre><code> 1. 声明关系
</code></pre>
</li>
<li><pre><code>     @OneToMany: 配置一对多的关系
</code></pre>
</li>
<li><pre><code>         targetEntity： 对方对象的字节码对象
</code></pre>
</li>
<li></li>
<li><pre><code> 2. 配置外键（中间表）
</code></pre>
</li>
<li><pre><code>     @JoinColum: 配置外键
</code></pre>
</li>
<li><pre><code>         name： 外键字段名称
</code></pre>
</li>
<li><pre><code>         referencedColumnName： 参照的主表的主键字段名称
</code></pre>
</li>
<li>在客户实体类上（一的一方）添加了外键配置， 所以对于客户而言，也具备了维护外键的作用</li>
<li>  *&#x2F;<br> @OneToMany(targetEntity &#x3D; LinkMan.class)<br> @JoinColumn(name &#x3D; “lkm_usr_id”,referencedColumnName &#x3D; “id”)<br> private Set<LinkMan> linkManSet &#x3D; new HashSet<LinkMan>();</li>
</ul>
<p> 测试方法<br> @Test<br> @Transactional<br> @Rollback(false)<br> public void testAdd(){<br>     User user &#x3D; new User();<br>     user.setUsername(“tian”);<br>     user.setPassword(“tsq”);</p>
<pre><code> LinkMan linkMan = new LinkMan();
 linkMan.setLkmName(&quot;lv&quot;);
 linkMan.setLkmPhone(&quot;1314&quot;);


 linkMan.setUser(user);
 user.getLinkManSet().add(linkMan);

 userDao.save(user);
 linkManDao.save(linkMan);
</code></pre>
<p> }</p>
<p> &#x2F;&#x2F;放弃外键维护权	<br> mappedBy: 对方配置关系的属性名称<br> @OneToMany(mappedBy &#x3D; “user”)<br> private Set<LinkMan> linkManSet &#x3D; new HashSet<LinkMan>();</p>
<p> &#x2F;&#x2F;级联操作<br> 在操作主体的实体类上配置cascade属性</p>
<p> cascade: 配置级联 CascadeType.<br> @OneToMany(mappedBy &#x3D; “user”, cascade &#x3D; CascadeType.ALL)<br> private Set<LinkMan> linkManSet &#x3D; new HashSet<LinkMan>();</p>
</li>
<li><p>多对多操作<br> 案例： 用户和角色<br>     用户:<br>     角色：<br> 分析步骤：<br>     1. 明确表关系<br>         多对多<br>     2. 确定表关系（描述 外键&#x2F;中间表）<br>         中间表<br>     3. 编写实体类，在实体类中描述表关系（包含关系）<br>         用户：包含角色的集合<br>         角色：包含用户的集合<br>     4. 配置映射关系<br><br><br> User.java<br> &#x2F;&#x2F;声明关系<br> @MangToMany(targetEntity &#x3D; Role.class) &#x2F;&#x2F;多对多 targetEntity: 代表对方的实体类字节码<br> &#x2F;&#x2F;配置中间表(包含两个外键)<br> @JoinTable(name &#x3D; “sys_user_role”,   &#x2F;&#x2F;中间表的名字<br>     &#x2F;&#x2F;joinColums, 当前对象在中间表中的外键 name 外键名,即中间表中列的名字 referencedColumnName 参照的主表的主键名<br>     joinColums &#x3D;{@JoinColum(name&#x3D;”sys_user_id”,referencedColumnName &#x3D; “user_id”)},<br>     &#x2F;&#x2F;inverseJoinColumns, 对方对象在中间表的外键<br>     inverseJoinColumns &#x3D; {@JoinColumn(name &#x3D; “sys_role_id”, referencedColumnName &#x3D; “role_id”)}<br> )<br> private Set<Role> roles &#x3D; new HashSet&lt;&gt;();<br><br><br> Role.java<br> &#x2F;&#x2F;声明关系<br> @MangToMany(targetEntity &#x3D; User.class) &#x2F;&#x2F;多对多 targetEntity: 代表对方的实体类字节码<br> &#x2F;&#x2F;配置中间表(包含两个外键)<br> @JoinTable(name &#x3D; “sys_user_role”,   &#x2F;&#x2F;中间表的名字<br>     &#x2F;&#x2F;joinColums, 当前对象在中间表中的外键 name 外键名 referencedColumnName 参照的主表的主键名<br>     joinColums &#x3D;{@JoinColum(name&#x3D;”sys_role_id”,referencedColumnName &#x3D; “role_id”)},<br>     &#x2F;&#x2F;inverseJoinColumns, 对方对象在中间表的外键<br>     inverseJoinColumns &#x3D; {@JoinColumn(name &#x3D; “sys_user_id”, referencedColumnName &#x3D; “user_id”)}<br> )<br> private Set<User> users &#x3D; new HashSet&lt;&gt;();<br><br><br> *多对多放弃维护权, 被动的一方放弃维护权<br> 角色被用户选择, 所以角色放弃维护权<br> Role.java<br> &#x2F;&#x2F;声明关系<br> @MangToMany(mappedBy &#x3D; “roles”)<br> private Set<User> users &#x3D; new HashSet&lt;&gt;();<br><br><br><br> *级联操作<br> 只操作User对象,因此在User上配置<br> User.java<br> &#x2F;&#x2F;声明关系<br> @MangToMany(targetEntity &#x3D; Role.class, cascade&#x3D;CascadeType.ALL) &#x2F;&#x2F;多对多 targetEntity: 代表对方的实体类字节码</p>
</li>
<li><p>多表查询</p>
<ol>
<li>对象导航查询<br> 查询一个对象的同时, 通过此对象查询他的关联对象<br> &#x2F;&#x2F;测试对象导航查询(查询一个对象的同时, 通过此对象查询他的关联对象)<br> @Test<br> @Transactional  &#x2F;&#x2F;解决java代码中 no session问题报错<br> public void testQuery1(){<br> &#x2F;&#x2F;查询id为1的用户<br> User one &#x3D; userDao.getOne(11);<br> &#x2F;&#x2F;对象导航查询, 查询此用户下的所有联系人<br> Set<LinkMan> linkManSet &#x3D; one.getLinkManSet();<br> for (LinkMan linkMan : linkManSet) {<br> System.out.println(linkMan);<br> }<br> }</li>
</ol>
<p> 对于对象导航查询, 默认使用的延迟加载的形式查询, 调用getLinkManSet方法并不会立即查询, 而是使用关联对象时才会查询<br> 不想用延迟加载则需要修改配置fetch到@OneToMany()注解中<br> &#x2F;&#x2F;EAGER: 立即加载  LAZY: 延迟加载<br> @OneToMany(fetch &#x3D; FetchType.EAGER)</p>
<p> &#x2F;&#x2F;从联系人对象导航查询所属联系人</p>
<p> &#x2F;&#x2F;多查一, 默认立即加载<br> @Test<br> @Transactional  &#x2F;&#x2F;解决java代码中 no session问题报错<br> public void testQuery2(){<br>     &#x2F;&#x2F;从联系人查询所属用户<br>     LinkMan linkMan &#x3D; linkManDao.findOne(1);<br>     User user &#x3D; linkMan.getUser();<br>     System.out.println(user);</p>
<p> }</p>
</li>
</ol>
<p>	</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/shiqing/about" rel="external nofollow noreferrer">世庆</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shiqing.gitee.io/shiqing/2021/04/23/java-kuang-jia/springjpa/">https://shiqing.gitee.io/shiqing/2021/04/23/java-kuang-jia/springjpa/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/shiqing/about" target="_blank">世庆</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/shiqing/tags/SpringJPA/">
                                    <span class="chip bg-color">SpringJPA</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/shiqing/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/shiqing/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/shiqing/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/shiqing/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/shiqing/2021/04/26/suan-fa/sortsollutions/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/9.jpg" class="responsive-img" alt="SortSollutions.md">
                        
                        <span class="card-title">SortSollutions.md</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-04-26
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">排序算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/shiqing/2021/04/23/tensorflow2/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/5.jpg" class="responsive-img" alt="tensorflow2">
                        
                        <span class="card-title">tensorflow2</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-04-23
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Python/" class="post-category">
                                    Python
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Tensorflow/">
                        <span class="chip bg-color">Tensorflow</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/shiqing/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/shiqing/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




        <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/shiqing/about" target="_blank">ShiQing</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2528393970@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2528393970" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2528393970" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/shiqing/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/shiqing/search.xml', 'searchInput', 'searchResult');
});
</script>

        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


        <script src="/shiqing/libs/materialize/materialize.min.js"></script>
        <script src="/shiqing/libs/masonry/masonry.pkgd.min.js"></script>
        <script src="/shiqing/libs/aos/aos.js"></script>
        <script src="/shiqing/libs/scrollprogress/scrollProgress.min.js"></script>
        <script src="/shiqing/libs/lightGallery/js/lightgallery-all.min.js"></script>
        <script src="/shiqing/js/matery.js"></script>

        <!-- Baidu Analytics -->

        <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

        
        <script src="/shiqing/libs/others/clicklove.js" async="async"></script>
        
        
        <script async src="/shiqing/libs/others/busuanzi.pure.mini.js"></script>
        

        <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我~看不见我~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script>

        <!-- 背景樱花飘落特效 -->
        
            <script type="text/javascript">
                //只在桌面版网页启用特效
                var windowWidth = $(window).width();
                if (windowWidth > 768) {
                    document.write('<script type="text/javascript" src="/js/xuehuapiaoluo.js"><\/script>');
                }
            </script>
        

        

        


        
        

        

        

        
        <script src="/shiqing/libs/instantpage/instantpage.js" type="module"></script>
        

    </body>

</html>
